package com.ryl.yomall.rabbitmq.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ryl.yomall.rabbitmq.pojo.YomallCorrelationData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Date 17:43
 * @Author ryl
 * 发送消息后,回调类
 */
@Component
@Slf4j
public class MQProducerAckConfig implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostConstruct
    public void init(){
        this.rabbitTemplate.setConfirmCallback ( this );
        this.rabbitTemplate.setReturnCallback ( this );
    }
    //交换机应答实现类
    // 成功与失败都应答
    //参数1： CorrelationData ： 消息发送的时候相关信息
    //参数2：ack : true 成功   false:失败
    //参数3： 成功应答 cause null 失败应答：失败的原因  404 NOT FOUND no exchange
    @Override
    public void confirm(CorrelationData correlationData ,boolean ack ,String cause) {

        System.out.println ("ack:"+ack );
        if (ack) {
            log.info("消息发送成功：" + JSON.toJSONString(correlationData));
        } else {
            log.info("消息发送失败：" + cause + " 数据：" + JSON.toJSONString(correlationData));
            retrySendMessage(correlationData);
        }

    }

    //重试
    private void retrySendMessage(CorrelationData correlationData) {
        YomallCorrelationData yomallCorrelationData= (YomallCorrelationData) correlationData;
        int retryCount = yomallCorrelationData.getRetryCount ( );
        if(++retryCount<3){
            yomallCorrelationData.setRetryCount ( retryCount  );
            redisTemplate.opsForHash ().put ( "rabbit:message",correlationData.getId (),JSONObject.toJSONString (  yomallCorrelationData));
        rabbitTemplate.convertAndSend ( yomallCorrelationData.getExchange ()
        ,yomallCorrelationData.getRoutingKey (),yomallCorrelationData.getMessage (),yomallCorrelationData);
        }else{
            log.info ( "重新发送次数已用完,请管理员处理"+yomallCorrelationData.toString () );
        }
    }

    //队列应答实现类
    //只能失败了才应答
    //参数1：Message ： 发送消息  消息头及体
    //参数2   replyCode : 失败码 404
    //参数3   replyCode : 失败英文说明  NOT Found
    //参数4  交换机
    //参数5   队列
    @Override
    public void returnedMessage(Message message ,int replyCode ,String replyText ,String exchange ,String routingKey) {
        // 反序列化对象输出
        System.out.println("消息主体: " + new String(message.getBody()));
        System.out.println("应答码: " + replyCode);
        System.out.println("描述：" + replyText);
        System.out.println("消息使用的交换器 exchange : " + exchange);
        System.out.println("消息使用的路由键 routing : " + routingKey);

        //在message的headers中存放了id
        String uuid = (String) message.getMessageProperties ( ).getHeaders ( ).get ( "spring_returned_message_correlation" );
        String o = (String) redisTemplate.opsForHash().get("rabbit:message", uuid);
        //把值json解析为对象
        YomallCorrelationData yomallCorrelationData = JSON.parseObject ( o ,YomallCorrelationData.class );
        if(yomallCorrelationData.isDelay()){
            System.out.println("不要重新发：是延迟插件造成的、算了吧");
            return;
        }

        System.out.println("开始重新发送");
        //重新发送
        this.retrySendMessage(yomallCorrelationData);
        System.out.println (message );
    }
}
